package com.currency.mall.ui.main.order;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.adapter.OrderBalanceAdapter;
import com.currency.mall.adapter.OrderEntrustAdapter;
import com.currency.mall.adapter.OrderPositionAdapter;
import com.currency.mall.entity.OrderInfo;
import com.currency.mall.entity.UserOrderBean;
import com.currency.mall.netWork.NetWork;
import com.currency.mall.ui.login.LoginActivity;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.commonbase.util.ToastUitl;
import com.ogaclejapan.smarttablayout.utils.v4.FragmentPagerItem;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/12/24.
 */

public class OrderStatusFragment extends BaseFragment {

    @BindView(R.id.rv_order_statu)
    RecyclerView rvOrderStatu;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.ll_not_data)
    RelativeLayout llNotData;
    private OrderBalanceAdapter mOrderBalanceAdapter;
    private OrderEntrustAdapter mOrderEntrustAdapter;
    private OrderPositionAdapter mOrderPositionAdapter;
    private int position = 0;
    private int mCurrentPage;
    private String status;//订单状态
    private List<OrderInfo> orderInfoList;
    private int pageSize = 20;
    private int currentSize;
    private Dialog hintDialogShow;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mView = inflater.inflate(R.layout.fragment_order_status, container, false);
        unbinder = ButterKnife.bind(this, mView);
        position = FragmentPagerItem.getPosition(getArguments());
        init();
        return mView;
    }

    private void init() {
        mCurrentPage = 1;
        orderInfoList = new ArrayList<>();
        setStatus();
        rvOrderStatu.setLayoutManager(new LinearLayoutManager(getContext()));
        rvOrderStatu.setNestedScrollingEnabled(false);
        refreshLayout.setEnableLoadMore(true);
        mOrderEntrustAdapter = new OrderEntrustAdapter(null, getContext());
        mOrderPositionAdapter = new OrderPositionAdapter(null, getContext());
        mOrderBalanceAdapter = new OrderBalanceAdapter(null, getContext());
        rvOrderStatu.setAdapter(mOrderBalanceAdapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (refreshLayout != null) {
                    mCurrentPage = 1;
                    getUserOrder(mCurrentPage);
                }
            }
        });
        mOrderPositionAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                OrderInfo orderInfo = orderInfoList.get(position);
                if (view.getId() == R.id.btn_entrust_settlement) {
                    if("false".equals(orderInfo.getSwitchClose())){
                            ToastUitl.show("委托认购确认后，第二天才可以提前行权",200);
                    }else{
                        Intent intent = new Intent(getContext(), EntrustSettlementActivity.class);
                        intent.putExtra("orderInfo", orderInfo);
                        startActivity(intent);
                    }

                }
            }
        });

        mOrderBalanceAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                OrderInfo orderInfo = orderInfoList.get(position);
                 if(view.getId() == R.id.iv_current_state){
                    hintDialogShow(orderInfo.getSuccessCloseTime());
                }
            }
        });
        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX,
                                       int oldScrollY) {
                //判断是否滑到的底部
                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
                    onLoadMoreRequested();
                }
            }
        });

        getUserOrder(1);
    }

    private void setStatus() {
        if (position == 0) {
            status = "ENTRUST";
        } else if (position == 1) {
            status = "POSITION";
        } else if (position == 2) {
            status = "CLOSE";
        }
    }

    public void onLoadMoreRequested() {
        if (currentSize >= pageSize) {
            mCurrentPage++;
            getUserOrder(mCurrentPage);
        }
    }

    public void getUserOrder(int page) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("status", status);
        hashMap.put("pageNum", page);
        hashMap.put("pageSize", pageSize);
        NetWork.getOderApi().userOrder(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserOrderBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        finishRefresh();
                    }

                    @Override
                    public void onNext(UserOrderBean userOrderBean) {
                        finishRefresh();
                        if (userOrderBean.getCode().equals(Constant.SUCCESS_CODE)) {
                            setData(userOrderBean.getPageList());
                        } else if (userOrderBean.getCode().equals("9112")) {
                            toLogin();
                        } else {
                            ToastUitl.show(userOrderBean.getMsg(), 200);
                        }
                    }
                });
    }

    private void setData(UserOrderBean.OrderPage orderPage) {
        currentSize = orderPage.getList().size();
        orderInfoList = orderPage.getList();
        if (orderInfoList.size() ==0) {
            llNotData.setVisibility(View.VISIBLE);
        } else {
            llNotData.setVisibility(View.GONE);
        }
        if (position == 0) {
            if (mCurrentPage == 1) {
                rvOrderStatu.setAdapter(mOrderEntrustAdapter);
                mOrderEntrustAdapter.setNewData(orderPage.getList());
            } else {
                orderInfoList.addAll(orderPage.getList());
                mOrderEntrustAdapter.addData(orderPage.getList());
                rvOrderStatu.setAdapter(mOrderEntrustAdapter);
            }
        } else if (position == 1) {
            if (mCurrentPage == 1) {
                mOrderPositionAdapter.setNewData(orderPage.getList());
                rvOrderStatu.setAdapter(mOrderPositionAdapter);
            } else {
                orderInfoList.addAll(orderPage.getList());
                mOrderPositionAdapter.addData(orderPage.getList());
                rvOrderStatu.setAdapter(mOrderPositionAdapter);
            }
        } else if (position == 2) {
            if (mCurrentPage == 1) {
                mOrderBalanceAdapter.setNewData(orderPage.getList());
                rvOrderStatu.setAdapter(mOrderBalanceAdapter);
            } else {
                orderInfoList.addAll(orderPage.getList());
                mOrderBalanceAdapter.addData(orderPage.getList());
                rvOrderStatu.setAdapter(mOrderBalanceAdapter);
            }

        }
    }

    public void finishRefresh() {
        if (refreshLayout != null)
            refreshLayout.finishRefresh();
    }

    public void toLogin() {
        Intent intent = new Intent(getContext(), LoginActivity.class);
        startActivity(intent);
    }

    private void hintDialogShow(String time) {
        hintDialogShow = new Dialog(getContext(), R.style.dialog);
        hintDialogShow.setContentView(R.layout.dialog_not_title);
        hintDialogShow.show();
        hintDialogShow.setCancelable(false);
        View view = (View)hintDialogShow.findViewById(R.id.v_view);
        TextView tvInfo = (TextView) hintDialogShow.findViewById(R.id.tv_info);
        if(time !=null){
            tvInfo.setText("当前订单在结算中，预计完成时间为："+time.substring(0,10));
        }else{
            tvInfo.setText("当前订单在结算中，预计完成时间为：");
        }
        Button okBtn = hintDialogShow.findViewById(R.id.bt_ok);
        view.setVisibility(View.GONE);
        okBtn.setVisibility(View.GONE);
        Button cancleBtn = hintDialogShow.findViewById(R.id.bt_cancle);
        cancleBtn.setText("知道了");
        cancleBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintDialogShow.dismiss();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
